<template>
    <view class="calendar" :class="{ 'dark': isDarkMode }" :style="themeStyle">
        <view class="calendar-header">
            <view class="arrow" @click="changeMonth(-1)">
                <text class="bigfont big-fanhui"></text>
            </view>
            <view class="current-date" @click="showDatePicker = true">{{ currentYear }}年{{ currentMonth + 1 }}月
            </view>
            <view class="arrow" @click="changeMonth(1)">
                <text class="bigfont big-youjiantoucu"></text>
            </view>
        </view>

        <!-- 修改日期选择器的属性绑定 -->
        <DatePicker ref="datePickerRef" v-model:visible="showDatePicker" :default-year="currentYear"
            :default-month="currentMonth + 1" :min-year="actualCurrentYear" :max-year="actualCurrentYear + 5"
            @confirm="onDatePickerConfirm" @cancel="showDatePicker = false" disablePastMonths />

        <view class="weekdays">
            <view v-for="day in weekDays" :key="day" class="weekday">{{ day }}</view>
        </view>

        <view class="days">
            <view class="calendar-decoration">
                <image src="https://files.bigtian.club/bigtian/2025/01/21/20250121142825A032.png" mode="aspectFit">
                </image>

            </view>
            <view v-for="(day, index) in days" :key="index" class="day-item" :class="{
                'empty': !day,
                'current': isCurrentDay(day),
                'selected': isSelectedDay(day),
                'disabled': isDateDisabled(day)
            }" @click="selectDate(day)">
                <template v-if="day">
                    <view class="day-number">{{ day.getDate() }}</view>
                    <view v-if="hasMarker(day)" class="day-marker"></view>
                    <slot :name="formatDate(day)" :date="day"></slot>

                </template>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { currentTheme, isDarkMode, themes } from '@/store/theme'
import { computed, defineEmits, defineProps, ref, watch } from 'vue'
import DatePicker from './DatePicker.vue'

const emit = defineEmits(['update:date', 'select', 'monthChange'])

const props = defineProps({
    initialDate: {
        type: Date,
        default: () => new Date()
    },
    markedDates: {
        type: Array as () => Date[],
        default: () => []
    },
    date: {
        type: Date,
        default: null
    }
})

const weekDays = ['日', '一', '二', '三', '四', '五', '六']
const currentDate = ref(props.initialDate)
const selectedDate = ref<Date | null>(props.date || props.initialDate)
const showDatePicker = ref(false)
const datePickerRef = ref<InstanceType<typeof DatePicker> | null>(null)

// 年月选择器数据
const years = Array.from({ length: 10 }, (_, i) => currentDate.value.getFullYear() - 5 + i)
const months = Array.from({ length: 12 }, (_, i) => i + 1)

const yearIndex = ref(years.indexOf(currentDate.value.getFullYear()))
const monthIndex = ref(currentDate.value.getMonth())

const tempYear = ref(currentDate.value.getFullYear())
const tempMonth = ref(currentDate.value.getMonth())

// 计算属性
const currentYear = computed(() => currentDate.value.getFullYear())
const currentMonth = computed(() => currentDate.value.getMonth())

// 获取实际的当前年份
const actualCurrentYear = computed(() => new Date().getFullYear())

// 获取当前主题颜色
const themeColors = computed(() => {
    const theme = themes.find(t => t.id === currentTheme.value)
    return theme ? theme.colors : themes[0].colors
})

// 转换颜色为rgba
const toRGBA = (hex: string, alpha: number) => {
    const r = parseInt(hex.slice(1, 3), 16)
    const g = parseInt(hex.slice(3, 5), 16)
    const b = parseInt(hex.slice(5, 7), 16)
    return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

// 计算主题相关的样式
const themeStyle = computed(() => ({
    '--theme-primary': themeColors.value.primary,
    '--theme-primary-alpha-08': toRGBA(themeColors.value.primary, 0.08),
    '--theme-primary-alpha-15': toRGBA(themeColors.value.primary, 0.15),
    '--theme-primary-alpha-30': toRGBA(themeColors.value.primary, 0.3),
    '--theme-bg': isDarkMode.value ? '#121212' : '#fff',
    '--theme-text': isDarkMode.value ? '#e0e0e0' : '#333',
    '--theme-text-light': isDarkMode.value ? '#888' : '#666',
    '--theme-border': isDarkMode.value ? '#2c2c2c' : '#f0f0f0',
    '--theme-component-bg': isDarkMode.value ? '#1e1e1e' : '#f8f9fa',
    '--theme-component-active': isDarkMode.value ? '#282828' : '#f0f1f2',
    '--theme-shadow': isDarkMode.value ? 'rgba(0, 0, 0, 0.3)' : 'rgba(0, 0, 0, 0.06)',
    '--theme-shadow-heavy': isDarkMode.value ? 'rgba(0, 0, 0, 0.5)' : 'rgba(0, 0, 0, 0.1)'
}))

// 监听初始日期变化
watch(() => props.initialDate, (newDate) => {
    currentDate.value = newDate
})

// 监听date prop变化
watch(() => props.date, (newDate) => {
    if (newDate) {
        selectedDate.value = newDate
        currentDate.value = newDate
    }
})

// 日期选择器确认回调
const onDatePickerConfirm = ({ year, month }: { year: number; month: number }) => {
    const newDate = new Date(year, month - 1)
    currentDate.value = newDate
    selectedDate.value = newDate // 同时更新选中的日期
    showDatePicker.value = false
    emit('update:date', newDate)
    emit('select', newDate)
    emit('monthChange', newDate)
}

// 检查日期是否有标记
const hasMarker = (day: Date | null) => {
    if (!day || !props.markedDates.length) return false
    return props.markedDates.some(markedDate =>
        markedDate.getDate() === day.getDate() &&
        markedDate.getMonth() === day.getMonth() &&
        markedDate.getFullYear() === day.getFullYear()
    )
}

// 计算当月的所有日期
const days = computed(() => {
    const year = currentDate.value.getFullYear()
    const month = currentDate.value.getMonth()
    const firstDay = new Date(year, month, 1)
    const lastDay = new Date(year, month + 1, 0)

    const days: (Date | null)[] = []

    // 填充月初空白天数
    for (let i = 0; i < firstDay.getDay(); i++) {
        days.push(null)
    }

    // 填充当月天数
    for (let i = 1; i <= lastDay.getDate(); i++) {
        days.push(new Date(year, month, i))
    }

    // 填充月末空白天数，只补充到完整的一周
    const remainingDays = 7 - (days.length % 7)
    if (remainingDays < 7) {
        for (let i = 0; i < remainingDays; i++) {
            days.push(null)
        }
    }

    return days
})

// 切换月份
const changeMonth = (delta: number) => {
    const newDate = new Date(currentDate.value)
    newDate.setMonth(newDate.getMonth() + delta)
    currentDate.value = newDate
    emit('monthChange', newDate)
}

// 判断是否是当天
const isCurrentDay = (day: Date | null) => {
    if (!day) return false
    const today = new Date()
    return day.getDate() === today.getDate() &&
        day.getMonth() === today.getMonth() &&
        day.getFullYear() === today.getFullYear()
}

// 判断是否是选中日期
const isSelectedDay = (day: Date | null) => {
    if (!day || !selectedDate.value) return false
    return day.getDate() === selectedDate.value.getDate() &&
        day.getMonth() === selectedDate.value.getMonth() &&
        day.getFullYear() === selectedDate.value.getFullYear()
}

// 选择日期
const selectDate = (day: Date | null) => {
    if (!day || isDateDisabled(day)) return
    selectedDate.value = new Date(day.getTime()) // 创建新的Date对象以避免引用问题
    emit('update:date', selectedDate.value)
    emit('select', selectedDate.value)
}

// 格式化日期为插槽名称
const formatDate = (day: Date): string => {
    return `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`
}

// 判断日期是否禁用
const isDateDisabled = (day: Date | null) => {
    if (!day) return false
    return datePickerRef.value?.isDateDisabled(day.getFullYear(), day.getMonth() + 1) || false
}
</script>

<style scoped>
.calendar {
    background: var(--theme-bg);
    border-radius: 24rpx;
    padding: 20rpx 16rpx;
    box-shadow: 0 8rpx 32rpx var(--theme-shadow);
    transition: all 0.3s ease;
    overflow: hidden;
    position: relative;
    width: 100%;
    box-sizing: border-box;
}

.dark .calendar {
    border: 1rpx solid var(--theme-border);
}

.calendar-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 0 20rpx;
}

.current-date {
    font-size: 28rpx;
    font-weight: 600;
    color: var(--theme-text);
    background: var(--theme-component-bg);
    padding: 12rpx 24rpx;
    border-radius: 32rpx;
    transition: all 0.3s ease;
    box-shadow: 0 2rpx 8rpx var(--theme-shadow);
}

.current-date:active {
    background: var(--theme-component-active);
    transform: scale(0.98);
}

.arrow {
    width: 56rpx;
    height: 56rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s ease;
    background: var(--theme-component-bg);
    margin: 0 4rpx;
    color: var(--theme-text);
}

.arrow:active {
    background: var(--theme-component-active);
    transform: scale(0.95);
}

.weekdays {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    text-align: center;
    padding: 12rpx 0;
    margin: 0;
}

.weekday {
    font-size: 24rpx;
    color: var(--theme-text-light);
    font-weight: 500;
    padding: 8rpx 0;
}

.days {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 6rpx;
    padding: 6rpx;
    position: relative;
    margin: 0;
}

.day-item {
    aspect-ratio: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    z-index: 2;
    border-radius: 8rpx;
    transition: all 0.3s ease;
    padding: 2rpx;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.day-item:active {
    transform: scale(0.95);
}

.day-number {
    font-size: 26rpx;
    color: var(--theme-text);
    margin-bottom: 4rpx;
    font-weight: 400;
}

.empty {
    pointer-events: none;
}

.current {
    color: var(--theme-primary);
    font-weight: 600;
    background: var(--theme-primary-alpha-08);
}

.dark .current {
    background: var(--theme-primary-alpha-15);
    box-shadow: 0 2rpx 8rpx var(--theme-shadow);
}

.selected {
    background: var(--theme-primary) !important;
    border-radius: 8rpx;
    box-shadow: 0 2rpx 8rpx var(--theme-primary-alpha-30);
    transform-origin: center;
}

.selected:active {
    transform: scale(0.95);
    transform-origin: center;
}

.selected .day-number {
    color: #fff !important;
    font-weight: 600;
}

.current.selected {
    background: var(--theme-primary) !important;
}

.dark .current.selected {
    background: var(--theme-primary) !important;
}

.current.selected .day-number {
    color: #fff !important;
}

/* 年月选择器样式优化 */
.picker-container {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 998;
}

.picker-mask {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    backdrop-filter: blur(8px);
}

.dark .picker-mask {
    background: rgba(0, 0, 0, 0.8);
}

.year-month-picker {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: var(--theme-bg);
    z-index: 999;
    border-radius: 32rpx 32rpx 0 0;
    box-shadow: 0 -4rpx 24rpx var(--theme-shadow);
    animation: slideUp 0.3s ease-out;
    transition: all 0.3s ease;
}

.dark .year-month-picker {
    border-top: 1rpx solid var(--theme-border);
}

.picker-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 28rpx 32rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: var(--theme-text);
    border-bottom: 1rpx solid var(--theme-border);
}

.close-icon {
    font-size: 44rpx;
    color: var(--theme-text-light);
    line-height: 1;
    padding: 12rpx;
    border-radius: 50%;
    background: var(--theme-component-bg);
    width: 44rpx;
    height: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.picker-view {
    height: 480rpx;
    text-align: center;
}

.picker-item {
    line-height: 88rpx;
    font-size: 34rpx;
    color: var(--theme-text);
    font-weight: 400;
}

.picker-buttons {
    display: flex;
    justify-content: space-between;
    padding: 24rpx 32rpx 32rpx;
}

.picker-btn {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 30rpx;
    border-radius: 40rpx !important;
    border: none;
    text-align: center;
    transition: all 0.2s ease;
    padding: 0;
}

.cancel-btn {
    color: var(--theme-text);
    background: var(--theme-component-bg);
    border: none !important;
    outline: none !important;
    box-shadow: none !important;
}

.confirm-btn {
    color: #fff;
    background: var(--theme-primary);
    font-weight: 500;
    box-shadow: 0 4rpx 12rpx var(--theme-primary-alpha-30);
}

.picker-btn:active {
    transform: scale(0.96);
    opacity: 0.9;
}

.day-marker {
    width: 6rpx;
    height: 6rpx;
    border-radius: 50%;
    background-color: var(--theme-primary);
    margin-top: 4rpx;
}

/* 装饰图片样式优化 */
.calendar-decoration {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 240rpx;
    height: 240rpx;
    opacity: 0.4;
    pointer-events: none;
    z-index: 1;
}

.dark .calendar-decoration {
    opacity: 0.5;
}

.calendar-decoration image {
    width: 100%;
    height: 100%;
    object-fit: contain;
}
</style>